package cn.sczc.jh.client.websocket;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

import cn.sczc.jh.client.websocket.encoder.WebSocketMessageEncoder;

@ServerEndpoint(value = "/websocket/devices/{id}", encoders = { WebSocketMessageEncoder.class })
@Component
public class WirelessDeviceWebSocket {
	private final static Logger logger = LogManager.getLogger(WirelessDeviceWebSocket.class);
	// 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
	private static int onlineCount = 0;
	// concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
	private static CopyOnWriteArraySet<WirelessDeviceWebSocket> webSocketSet = new CopyOnWriteArraySet<WirelessDeviceWebSocket>();

	// 与某个客户端的连接会话，需要通过它来给客户端发送数据
	private Session session;

	// 接收sid
	private String id = "";

	/**
	 * 连接建立成功调用的方法
	 */
	@OnOpen
	public void onOpen(Session session, @PathParam("id") String id) {
		this.session = session;
		webSocketSet.add(this); // 加入set中
		addOnlineCount(); // 在线数加1
		logger.info("有新窗口开始监听,deviceId=" + id + ",当前在线人数为" + getOnlineCount());
		this.id = id;
	}

	/**
	 * 连接关闭调用的方法
	 */
	@OnClose
	public void onClose() {
		webSocketSet.remove(this); // 从set中删除
		subOnlineCount(); // 在线数减1
		logger.info("有一连接关闭！当前在线人数为" + getOnlineCount());
	}

	/**
	 * 收到客户端消息后调用的方法
	 *
	 * @param message 客户端发送过来的消息
	 */
	@OnMessage
	public void onMessage(String message, Session session) {
		logger.info("收到来自窗口" + this.id + "的信息:" + message);
	}

	/**
	 * 
	 * @param session
	 * @param error
	 */
	@OnError
	public void onError(Session session, Throwable error) {
		logger.error("发生错误", error);
	}

	/**
	 * 实现服务器主动推送
	 * 
	 * @throws EncodeException
	 */
	public synchronized void sendMessage(Object message) {
		try {
			if (this.session.isOpen()) {
				this.session.getAsyncRemote().sendObject(message);
			} else {
				logger.warn("连接已关闭，发送websocket消息失败！");
			}
		} catch (Exception e) {
			logger.error("", e);
		}
	}

	/**
	 * 群发自定义消息
	 */
	public static void sendMessage(Object message, @PathParam("id") String id) throws IOException {
//		logger.info("推送消息到窗口" + ip + "，推送内容:" + message);
		for (WirelessDeviceWebSocket item : webSocketSet) {
			try {
				if (item.id.equals(id)) {
					item.sendMessage(message);
				}
			} catch (Exception e) {
				logger.error(e);
			}
		}
	}

	public static synchronized int getOnlineCount() {
		return onlineCount;
	}

	public static synchronized void addOnlineCount() {
		WirelessDeviceWebSocket.onlineCount++;
	}

	public static synchronized void subOnlineCount() {
		WirelessDeviceWebSocket.onlineCount--;
	}
}
